import { defineStore } from 'pinia'

const USER_INFO_KEY = 'userInfo'
const PERMISSIONS_KEY = 'permissions'
const USER_INFO_EXPIRES_KEY = 'userInfoExpiresAt'
const TTL = 2 * 60 * 60 * 1000; // 2小时

export const useUserStore = defineStore('user', {
  state: () => {
    const expiresAt = Number(localStorage.getItem(USER_INFO_EXPIRES_KEY) || '0');
    const isExpired = expiresAt && Date.now() > expiresAt;
    const userInfo = !isExpired ? JSON.parse(localStorage.getItem(USER_INFO_KEY) || 'null') : null;
    const permissions = !isExpired ? JSON.parse(localStorage.getItem(PERMISSIONS_KEY) || '[]') : [];
    if (isExpired) {
      localStorage.removeItem(USER_INFO_KEY);
      localStorage.removeItem(PERMISSIONS_KEY);
      localStorage.removeItem(USER_INFO_EXPIRES_KEY);
    }
    return {
      userInfo,
      permissions,
    }
  },
  actions: {
    setUserInfo(info: { id: string; name: string }) {
      this.userInfo = info
      const expiresAt = Date.now() + TTL;
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(info))
      localStorage.setItem(USER_INFO_EXPIRES_KEY, expiresAt.toString())
    },
    setPermissions(perms: string[]) {
      this.permissions = perms
      localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(perms))
    },
    hasPermission(permission: string) {
      return this.permissions.includes(permission)
    },
    clear() {
      this.userInfo = null
      this.permissions = []
      localStorage.removeItem(USER_INFO_KEY)
      localStorage.removeItem(PERMISSIONS_KEY)
      localStorage.removeItem(USER_INFO_EXPIRES_KEY)
    }
  }
})
